package com.magicsoft.share.ui.my;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.magicsoft.share.R;
import com.magicsoft.share.base.BaseActivity;
import com.magicsoft.share.bean.my.JsonBean;
import com.magicsoft.share.bean.my.UserInfo;
import com.magicsoft.share.customview.alertview.AlertView;
import com.magicsoft.share.customview.alertview.OnItemClickListener;
import com.magicsoft.share.presenter.my.PersonalInfoPresenter;
import com.magicsoft.share.utils.OssTool;
import com.magicsoft.share.utils.PhotoTool;
import com.magicsoft.share.utils.ToastUtils;
import com.magicsoft.share.view.my.IPersonalInfoView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

import static com.magicsoft.share.constant.Constant.REFRESH_UI;
import static com.magicsoft.share.utils.PhotoTool.imageUriFromCamera;

public class PersonalInfoActivity extends BaseActivity<IPersonalInfoView, PersonalInfoPresenter> implements IPersonalInfoView {


    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ibtn_left)
    ImageButton ibtnLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_head)
    RoundedImageView ivHead;
    @BindView(R.id.layout_head_img)
    RelativeLayout layoutHeadImg;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.layout_id)
    RelativeLayout layoutId;
    @BindView(R.id.layout_name)
    RelativeLayout layoutName;
    @BindView(R.id.layout_sing)
    RelativeLayout layoutSing;
    @BindView(R.id.layout_birthday)
    RelativeLayout layoutBirthday;
    @BindView(R.id.layout_address)
    RelativeLayout layoutAddress;
    private AlertView alertView;
    private OptionsPickerView pvOptions;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private String TAG = "PersonalInfoActivity";
    private int mResultCode;

    private boolean isLoaded = false;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了


                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    //  Toast.makeText(PersonalInfoActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(PersonalInfoActivity.this, "解析城市数据失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;

            }
        }
    };
    private List<LocalMedia> selectList;
    private OssTool ossManager;
    private SweetAlertDialog dialog;


    @Override
    public PersonalInfoPresenter initPresenter() {
        return new PersonalInfoPresenter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_personal_info;
    }

    @Override
    public void initData() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        ossManager = OssTool.getInstance().init(this);
    }

    @Override
    public void initView() {
        tvTitle.setText("个人设置");
        initDialog();


    }


    @Override
    public void requestData() {
        mPresenter.userDetail();
    }


    @OnClick({R.id.ibtn_left, R.id.layout_head_img, R.id.layout_name, R.id.layout_sing, R.id.tv_id, R.id.layout_birthday, R.id.layout_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_left:
                finish();
                break;
            case R.id.layout_head_img:
                initAlertView();
                break;
            case R.id.layout_name:
                startActivityForResult(new Intent(this, NickNameActivity.class), REFRESH_UI);
                break;
            case R.id.layout_sing:
                startActivityForResult(new Intent(this, SignActivity.class), REFRESH_UI);
                break;
            case R.id.tv_id:
                break;
            case R.id.layout_birthday:
                initDatePick();
                break;
            case R.id.layout_address:
                if (isLoaded) {
                    ShowPickerView();
                }
                break;
        }
    }


    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2) + "-" +
                        options3Items.get(options1).get(options2).get(options3);

                mPresenter.editUserDetail(null, null, null, tx, null);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        Log.d(TAG, "initJsonData: 1");


        String JsonData = getJson("province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        Log.d(TAG, "initJsonData: 1");
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    private String getJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = this.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    private void initDatePick() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(1965, 0, 1);
        // endDate.set(2020,11,31);
        //时间选择器
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                mPresenter.editUserDetail(null, null, null, null, getTime(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false}).setRangDate(startDate, endDate)//起始终止年月日设定
                .build();
        pvTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private void initAlertView() {
        alertView = new AlertView(null, null, "取消", null,
                new String[]{"拍照", "我的相册"},
                this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 1) {
                    takePhoto();
                } else if (position == 0) {
                   requestPermissions();
                }
            }
        });
        alertView.show();
    }

    @Override
    public void userDetailSuccess(UserInfo data) {
        Glide.with(this).load(data.getHeadimg()).into(ivHead);
        tvName.setText(data.getNickname());
        tvSign.setText(data.getPersonalized_signature());
        tvBirthday.setText(data.getBirthday());
        tvAddress.setText(data.getRegion());
        if (data.getMember() == 0) {
            layoutId.setVisibility(View.GONE);
        } else {
            tvId.setText(data.getQixiang_no());
        }

    }

    @Override
    public void editUserDetailSuccess() {

        requestData();
        //  setResult(RESULT_OK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if ((requestCode == PictureConfig.CHOOSE_REQUEST)) {
                dialog.show();
                // 图片选择结果回调
                Log.d(TAG, "onActivityResult: ");
                selectList = PictureSelector.obtainMultipleResult(data);
                String compressPath = selectList.get(0).getCompressPath();

                ossManager.upload("headImg", compressPath, new OssTool.uploadListener() {


                    @Override
                    public void onSuccess(final String url) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dialog.dismiss();
                                mPresenter.editUserDetail(null, url, null, null, null);
                                Log.d(TAG, "onSuccess: " + url);
                            }
                        });

                    }

                    @Override
                    public void onFail() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dialog.dismiss();
                                Log.d(TAG, "onFail: ");
                                ToastUtils.showToast(PersonalInfoActivity.this, "更换头像失败，请重试");
                            }
                        });

                    }
                });
            } else if (resultCode == PhotoTool.GET_IMAGE_BY_CAMERA) {
                Uri imageUri = imageUriFromCamera;


                uploadOssImg(imageUri);
            }

        }
    }

    @Override
    protected void onRestart() {
        Log.d(TAG, "onRestart: ");
        super.onRestart();
        setResult(mResultCode);
    }


    private void takePhoto() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(PersonalInfoActivity.this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                .theme(R.style.picture_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                // .previewVideo()// 是否可预览视频 true or false
                // .enablePreviewAudio() // 是否可播放音频 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                // .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                //    .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //     .enableCrop()// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                // .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                //  .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                //  .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                .isGif(true)// 是否显示gif图片 true or false
                //.compressSavePath("/CustomPath")//压缩图片保存地址
                //   .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                //   .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                //    .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                //   .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                //     .selectionMedia(false)// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                // .cropCompressQuality()// 裁剪压缩质量 默认90 int
                //   .minimumCompressSize(100)// 小于100kb的图片不压缩
                //    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                // .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                //   .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                //  .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                //   .videoQuality()// 视频录制质量 0 or 1 int
                // .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                //  .recordVideoSecond()//视频秒数录制 默认60s int
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


    private void initDialog() {
        dialog = new SweetAlertDialog(PersonalInfoActivity.this, SweetAlertDialog.PROGRESS_TYPE);
        dialog.getProgressHelper().setBarColor(R.color.main);
        dialog.setTitleText("加载图片中...");
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {

                ossManager.cancel();
            }
        });
    }

    private void uploadOssImg(final Uri imageUri) {

        String path = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            path = PhotoTool.getImageAbsolutePath(this, imageUri);

        } else {
            path = PhotoTool.getRealFilePath(this, imageUri);

        }
        Date date = new Date();
        long time = date.getTime();
        ossManager.upload("headImg" + time, path, new OssTool.uploadListener() {


            @Override
            public void onSuccess(final String url) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        mPresenter.editUserDetail(null, url, null, null, null);
                        Log.d(TAG, "onSuccess: " + url);
                    }
                });

            }

            @Override
            public void onFail() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        Log.d(TAG, "onFail: ");
                        ToastUtils.showToast(PersonalInfoActivity.this, "更换头像失败，请重试");
                    }
                });

            }
        });
    }

    private void requestPermissions() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.CAMERA).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull Boolean aBoolean) {
                if (!aBoolean) {
                    ToastUtils.showToast(PersonalInfoActivity.this, "获取权限失败，部分功能将无法使用！");
                }else {
                    PhotoTool.openCameraImage(PersonalInfoActivity.this);
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }
}


